<template>
  <div class="login_content" @keydown="onKeyDown">
    <el-row>
      <el-col :span="12" :xs="0"></el-col>
      <!-- 右侧表单部分 -->
      <el-col :span="12" :xs="24" class="right">
        <div class="right-tip">
          <h1>Hello</h1>
          <h2>欢迎来到星辰集市后台管理系统</h2>
        </div>
        <div class="right-form">
          <el-form :model="loginForm" :rules="rules" ref="loginForms">
            <el-form-item prop="username">
              <el-input placeholder="请输入用户名" v-model="loginForm.username" :prefix-icon="User"></el-input>
            </el-form-item>
            <el-form-item prop="password">
              <el-input placeholder="请输入密码" v-model="loginForm.password" :prefix-icon="Lock" show-password></el-input>
            </el-form-item>
            <el-form-item>
              <!-- 验证码部分 -->
              <div class="form-item-captcha">
                <div class="captcha-box">
                  <input class="captcha-input" v-model="loginForm.captchaCode" @input="onCaptchaInput" placeholder="请输入验证码" type="text">
                  <img class="captcha-picture" :src="loginForm.imageBase64Url" @click="captchImgChange" alt="验证码图片" title="看不清换一张">
                </div>
                <!-- 提示信息 -->
                <span class="captcha-tip">{{ imageCaptchaTip }}</span>
              </div>
            </el-form-item>
            <el-form-item>
              <el-button type="primary" :loading="isLoading" class="login_btn" @click="login_btn">登录</el-button>
            </el-form-item>
          </el-form>
        </div>
      </el-col>
    </el-row>
  </div>
</template>

<script setup lang="ts">
import { ElRow, ElCol, ElForm, ElFormItem, ElInput, ElButton } from "element-plus";
import { User, Lock } from '@element-plus/icons-vue';
import { reactive, ref, onMounted } from "vue";
//引入elment-plus
import { ElMessage, ElNotification } from 'element-plus';
//@ts-ignore
import useUserStore from "@/store/user.ts";  //引入仓库
const userStore = useUserStore();
//引入路由器
import { useRouter,useRoute } from 'vue-router';
const router = useRouter();
const route = useRoute();
//@ts-ignore引入请求函数
import { reqPictureCaptcha } from "@/api/login/index.ts";
//登录表单部分
let loginForm = reactive({
  username:"admin",
  password:"123456",
  captchaCode:"",  //验证码
  imageBase64Url:"",  //base64验证码图片地址
})
let imageCaptchaTip = ref("");  //图片验证码提示信息
let isLoading = ref(false);

//登录表单校验规则
const loginForms = ref();  //表单组件实例
const validateUsername = (rule: any, value: any, callback: any) => {
  if (value === '' || value.length<2) {
    callback(new Error('请输入合法的用户名'))
  } else {
    callback();
  }
}
const validatePassword = (rule: any, value: any, callback: any) => {
  if (value === '') {
    callback(new Error('请输入密码'))
  } else if (value.length < 4){
    callback(new Error('密码长度不能少于四位'));
  } else {
    callback();
  }
}
const rules = reactive({
  username: [{ validator: validateUsername, trigger: 'blur' }],
  password: [{ validator: validatePassword, trigger: 'blur' }]
})

//验证码输入框的input事件
const onCaptchaInput = () => {
  if(loginForm.captchaCode.trim() !== "") {
    imageCaptchaTip.value = "";
  }
}
//点击验证码图片事件(重新请求验证码)
let timer:any = null;
const captchImgChange = () => {
  if(timer !== null) {
    clearTimeout(timer);
  }
  timer = setTimeout(() => {
    //请求验证码图片
    getPictureCaptcha();
  },500)
}

//回车键登录
const onKeyDown = (event:any) => {
  if(event.keyCode === 13){
    //触发登录按钮
    login_btn();
  }
}

//登录按钮
const login_btn = async () => {
  //校验表单
  try {
    await loginForms.value.validate();
  } catch (error) {
    return ElMessage({type:"error",message:"请输入合法的账号和密码"});
  }
  //验证码是否输入
  if(loginForm.captchaCode.trim() === "") return imageCaptchaTip.value = "提示:请输入验证码!";
  //进行登录操作
  try {
    //显示loadding效果
    isLoading.value = true;
    //调用仓库函数发送登录请求
    await userStore.userLogin(loginForm);
  } catch (error) {
    if(error.toString().includes("验证码错误")){
      isLoading.value = false;
      return imageCaptchaTip.value = "提示:验证码有误";
    }
    ElMessage({type:'error',message:'用户名或密码错误!'});
    isLoading.value = false;
    return;
  }
  //进行路由跳转
  let redirectpath:string = route.query.redirect as string;  //获取重定向路径信息
  if(redirectpath !== undefined){
    router.push(redirectpath);
  } else {
    router.push("/");
  }
  ElMessage({type:'success',message:'登陆成功!'});
  isLoading.value = false;
  showTime();
}
//展示通知信息时间处理
function showTime():void{
  let msg:string = '';
  let hours:number = new Date().getHours();
  let minutes:number = new Date().getMinutes();
  if(hours >= 0 && (hours < 5 || (hours == 5 && minutes <= 30))){
    msg = "夜深了";
  }else if((hours > 5 || (hours == 5 && minutes > 30)) && hours < 12){
    msg = "上午好";
  }else if(hours >= 12 && (hours < 18 || (hours == 18 && minutes <= 30))){
    msg = "下午好";
  }else if((hours > 18 || (hours == 18 && minutes > 30)) && (hours < 23 || (hours == 23 && minutes <= 30))){
    msg = "晚上好";
  }else if(hours == 23 && minutes > 30){
    msg = "夜深了";
  }
  //消息推送
  ElNotification({title: `Hi,${msg}!`,message: '欢迎回来',type: 'success',duration:4500,showClose:true});
}

//请求接口获取验证码图片(处理接口返回的base64编码的图片)
const getPictureCaptcha = async() => {
  let res = await reqPictureCaptcha();
  let url = "";
  let imageBase64 = ""
  if(res.code === 200) {
    //base64图片验证码获取成功
    if(!res.data.includes("data:image/png;base64,")){
      imageBase64 = "data:image/png;base64," + res.data;
    } else {
      imageBase64 = res.data;
    }
    //url = window.URL.createObjectURL(new Blob([imageBase64],{type:"image/png"}));  //转换成图片地址

    //将base64字符串转换为Blob对象
    let byteCharacters = atob(imageBase64.split(",")[1]);
    let byteNumbers = new Array(byteCharacters.length);
    for (var i = 0; i < byteCharacters.length; i++) {
      byteNumbers[i] = byteCharacters.charCodeAt(i);
    }
    let byteArray = new Uint8Array(byteNumbers);
    let blob = new Blob([byteArray], { type: 'image/png' }); // 根据实际图片格式设置type
    url = URL.createObjectURL(blob);
  }
  loginForm.imageBase64Url = url;
  console.log('图片验证码接口api',res);
  // console.log(imageBase64, url);
}

//vue生命周期
onMounted(async () => {
  //获取验证码图片
  getPictureCaptcha();
})
</script>

<style scoped lang="scss">
.login_content{
  width:100%;
  height:100vh;
  background: url('@/assets/images/manage_background.jpg') no-repeat no-repeat;
  background-size: cover;

  .right{
    position: relative;
    top:30vh;
    right:10vh;
    background: url('@/assets/images/login_form.png') no-repeat no-repeat;
    background-size: cover;
    padding: 20px 30px;

    .right-tip{
      margin-left: 5vw;
      color:white;

      h1{font-size: 30px;}
      h2{font-size: 16px;margin:20px 0;}
    }
    .right-form{
      width: 30vw;
      margin: 0 auto;

      /**验证码表单部分 */
      .form-item-captcha{
        width: 30vw;
        height: 48px;
        position: relative;
        .captcha-box {
          width: 30vw;
          height: 30px;
          display: flex;
          justify-content: space-between;
          align-items: center;
          .captcha-input{
            width: 21vw;
            height: 30px;
            padding: 0 12px;
            border-radius: 5px;
            border: none;
          }
          .captcha-input::-webkit-input-placeholder{
            font-size: 13px;
            color: #9195a3;
          }
          .captcha-picture{
            width: 8vw;
            height: 30px;
            background-color: #fff;
            cursor: pointer;
          }
          .captcha-picture:hover{
            opacity: 0.5;
          }
        }
        .captcha-tip{
          position: relative;
          left: 5px;
          top:-8px;
          font-size: 10px;
          color: #f00;
        }
      }
      .login_btn{
        width: 100%;
      }
    }
  }
}

</style>